import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import java.io.*;

public class HelloWorldClassFileTransformer implements ClassFileTransformer {
	public static void premain(String agentArgs, Instrumentation inst) {
		System.out.println("agentArgs:" + agentArgs);
		inst.addTransformer(new HelloWorldClassFileTransformer());
	}

	public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined,
			ProtectionDomain protectionDomain, byte[] classfileBuffer) {
		System.out.println("className:" + className);
		System.out.println("classBeingRedefined:" + classBeingRedefined);
		System.out.println("protectionDomain:" + protectionDomain);
		if( className.equals("HelloWorld") ) {
			//return readBytes("HelloWorld.class");
			return readBytes("../HelloWorld.class");
		}
		return null;
	}

	public static byte[] readBytes(String fileName) {
		System.out.println("file name:" + fileName);
		try {
			File file = new File(fileName);
			InputStream is = new FileInputStream(file);
			long length = file.length();
			byte[] bytes = new byte[(int)length];
			is.read(bytes);
			is.close();
			return bytes;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
}